package com.pi.shisan.i2c;

import com.pi.shisan.common.NumberUtil;
import com.pi.shisan.common.TextPxCreater;

import java.awt.image.BufferedImage;

/**
 * 可使用该类进行文字绘画
 */
public class OLEDTextUtil {

    /**
     * 在OLED屏幕上写一行字
     * @param display
     * @param text
     * @param x
     * @param y
     */
    public static int drawString(OLEDDisplay display, String text, int x, int y) {
        TextPxCreater.BoundsInfo boundsInfo = new TextPxCreater.BoundsInfo();
        int[] allPoints = TextPxCreater.getAllPointsSameLine(text, 12,boundsInfo);
        if (allPoints != null && allPoints.length > 0) {
            int px, py;
            int w = display.getWidth(), h = display.getHeight();
            for (int p : allPoints) {
                px = NumberUtil.toX(p) + x;
                py = NumberUtil.toY(p) + y;
                if (px < 0 || px >= w || py <0 || py >= h) {
                    continue;
                }
                display.setPixel(px, py, true);
            }
            return NumberUtil.toXy((short) boundsInfo.getMaxX(), (short) boundsInfo.getMaxY());
        }
        return 0;
    }

    public static void drawFromImage(OLEDDisplay display,BufferedImage image, int startX, int startY, int endX, int endY) {
        int[] points = TextPxCreater.getPoint(image, startX, startY);
        if (points != null && points.length > 0) {
            int px, py;
            int w = display.getWidth(), h = display.getHeight();
            if (endX > 0) {
                w = Math.min(w, endX);
            }
            if (endY > 0) {
                h = Math.min(h, endY);
            }
            for (int p : points) {
                px = NumberUtil.toX(p) + startX;
                py = NumberUtil.toY(p) + startY;
                if (px < 0 || px >= w || py <0 || py >= h) {
                    continue;
                }
                display.setPixel(px, py, true);
            }
        }
    }

}
